import json
import time
import uuid

import api as api
from DBAction import DBAction
from room import Room


class RoomInfoType:
    TITLE = 0  # 房间标题，显示在关注列表里的那个
    MEM_AVATAR = 1  # 头像，显示在房间里的
    ROOM_AVATAR = 2  # 头像，显示在关注列表里的
    TOPIC = 3  # 房间的主题
    BGIMG = 4  # 房间背景图片


class RoomBackup:
    '''这个类在合适的时候做备份，并把图片下载到本地'''

    def __init__(self, rid):
        self.rid = rid

    def update_room_used(self, type, value):
        db = DBAction('pocket48')
        db.data_operate("insert into roomused(roomid, type, info) values(%s, %s, %s)",
                        (self.rid, type, value))


class MessageType:
    TEXT = 'TEXT'  # 普通文字消息
    IMAGE = 'IMAGE'  # 图片消息
    EXPRESS = 'EXPRESS'  # 大表情
    AUDIO = 'AUDIO'  # 语音
    VIDEO = 'VIDEO'  # 视频
    # 下面是TEXT的类型，一般是普通文字消息
    REPLY = 'REPLY'  # 普通翻牌
    FLIPCARD = 'FLIPCARD'  # 鸡腿翻牌
    LIVEPUSH = 'LIVEPUSH'  # 直播
    VOTE = 'VOTE'  # 投票
    PASSWORD_REDPACKAGE = 'PASSWORD_REDPACKAGE'  # 红包消息
    FLIPCARD_AUDIO = 'FLIPCARD_AUDIO'  # 语音翻牌
    FLIPCARD_VIDEO = 'FLIPCARD_VIDEO'  # 视频翻牌

    @staticmethod
    def get_type(t, t2):
        if t == MessageType.TEXT:
            if t2 == MessageType.TEXT:
                return 0
            elif t2 == MessageType.REPLY:
                return 5
            elif t2 == MessageType.FLIPCARD:
                return 6
            elif t2 == MessageType.LIVEPUSH:
                return 7
            elif t2 == MessageType.VOTE:
                return 8
            elif t2 == MessageType.PASSWORD_REDPACKAGE:
                return 9
            elif t2 == MessageType.FLIPCARD_AUDIO:
                return 10
            elif t2 == MessageType.FLIPCARD_VIDEO:
                return 11
        elif t == MessageType.IMAGE:
            return 1
        elif t == MessageType.EXPRESS:
            return 2
        elif t == MessageType.AUDIO:
            return 3
        elif t == MessageType.VIDEO:
            return 4


class RoomMsg:
    def __init__(self, msg):
        '''传入消息的json'''
        # msg = json.dumps(msg)
        extinfo = json.loads(msg['extInfo'])
        self.id = msg['serverId']
        self.uuid = msg['msgidClient']
        self.memberid = extinfo['user']['userId']
        self.roomid = extinfo['roomId']
        self.msgTime = api.convert_timestamp_to_timestr(msg['msgTime'])
        self.bodys = msg['bodys']
        self.msgType = MessageType.get_type(msg['msgType'], extinfo['messageType'])
        if self.msgType == 0:
            self.extInfo = ""
        elif self.msgType == 1 or self.msgType == 3 or self.msgType == 4:  # IMAGE 语音或视频，extinfo里都保存url
            self.extInfo = json.loads(msg['bodys'])['url']  # TODO error_service_not_public 请求url会收到错误，后期解决
        elif self.msgType == 2:  # 大表情
            self.extInfo = ""
        elif self.msgType == 5:  # REPLY
            self.extInfo = extinfo['replyMessageId'] + ',' + extinfo['replyName'] + ',' + extinfo['replyText']
        elif self.msgType == 6:  # FLIPCARD
            self.extInfo = msg['extInfo']
        elif self.msgType == 7:  # LIVEPUSH
            self.extInfo = extinfo['liveId']
        elif self.msgType == 8:  # 投票
            self.extInfo = extinfo['text']
        elif self.msgType == 9:  # 口令红包
            self.extInfo = ""
        elif self.msgType == 10 or self.msgType == 11:  # 语音翻牌 视频翻牌
            self.extInfo = msg['extInfo']

    def save(self):
        db = DBAction('pocket48')
        db.data_operate("insert ignore into roommsg(id,memberid,roomid,uuid,msg_time,msg_type,bodys,ext_info) values(%s,%s,%s,%s,%s,%s,%s,%s)",
                        (self.id, self.memberid, self.roomid, self.uuid, self.msgTime, self.msgType, self.bodys, self.extInfo))


class Member:
    def __init__(self, id, rid):
        self.id = id
        self.room = Room(rid)

    def get_member_images(self):
        """
        获取成员动态里的部分图片，动态还需再研究
        """
        url = 'https://pocketapi.48.cn/posts/api/v1/posts/img/list'
        params = {
            "nextId": 0,
            "userId": self.id
        }
        response = api.post(url, params)
        if response['status'] == 200:
            print(response)

    def get_member_room_msg(self, nextTime=0):
        url = 'https://pocketapi.48.cn/im/api/v1/chatroom/msg/list/homeowner'
        params = {"needTop1Msg": "false", "roomId": str(self.room.roomid), "ownerId": str(self.id), "nextTime": str(nextTime)}
        response = api.post(url, params)
        api.wait_random_time(10)
        if response['status'] == 200:
            count = 0
            for msgdata in response['content']['message']:
                msg = RoomMsg(msgdata)
                msg.save()
                count += 1
            return response['content']['nextTime'], count
        else:
            return -1, 0

    def get_msg_last2now(self, endtime='2021-05-01 00:00:00', forcetime=None):
        '''当前时间开始取，直到数据库中上次的时间
        forcetime是强制取到这个时间，用于断线重连程序的正确'''
        if forcetime is None:
            db = DBAction('pocket48')
            result = db.data_inquiry_all('select max(msg_time) from roommsg where roomid=%s', self.room.roomid)
            last_time = result[0][0]
            if last_time is None:
                last_time = endtime
        else:
            last_time = forcetime

        last_time = api.convert_timestr_to_timestamp(last_time)
        ret = self.get_member_room_msg()
        timecursor = ret[0]
        while timecursor >= last_time:
            ret = self.get_member_room_msg(timecursor)
            timecursor = ret[0]
            count = ret[1]
            if timecursor == -1 or count == 0:
                break

    def get_msg_between(self, starttime, endtime):
        '''
        '''
        begin_time = api.convert_timestr_to_timestamp(starttime)
        endtime = api.convert_timestr_to_timestamp(endtime)
        timecursor = begin_time
        while timecursor >= endtime:
            print('get to time: ', api.convert_timestamp_to_timestr(timecursor))
            ret = self.get_member_room_msg(timecursor)
            timecursor = ret[0]
            count = ret[1]
            if timecursor == -1 or count == 0:
                break

    def get_msg_to_endtime(self, endtime):
        '''
        从数据库中最早的时间开始，直到endtime
        数据库没有任何记录，则从现在到endtime
        '''
        db = DBAction('pocket48')
        result = db.data_inquiry_all('select min(msg_time) from roommsg where roomid=%s', self.room.roomid)
        endtime = api.convert_timestr_to_timestamp(endtime)
        if len(result[0]) != 0:
            begin_time = result[0][0]
            if begin_time is None:
                begin_time = api.convert_timestr_to_timestamp(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
            else:
                begin_time = api.convert_timestr_to_timestamp(begin_time)
            print("begin_time:", api.convert_timestamp_to_timestr(begin_time))
            timecursor = begin_time
            while timecursor >= endtime:
                print('get to time: ', api.convert_timestamp_to_timestr(timecursor))
                ret = self.get_member_room_msg(timecursor)
                timecursor = ret[0]
                count = ret[1]
                if timecursor == -1 or count == 0:
                    break

    def update_avatar_and_fannum(self):
        '''更新头像和粉丝数'''
        url = 'https://pocketapi.48.cn/user/api/v1/user/info/home'
        params = {"userId": self.id}
        response = api.post(url, params)
        if response['status'] == 200:
            avatar = response['content']['baseUserInfo']['avatar']
            fannum = response['content']['baseUserInfo']['followers']
            db = DBAction('pocket48')
            db.data_operate("update member set fan_num=%s,avatar=%s where memberid=%s", (fannum, avatar, self.id))
        else:
            print(response)

    def get_fanpai_price(self):
        """更新翻牌价格"""
        url = r'https://pocketapi.48.cn/idolanswer/api/idolanswer/v1/custom/index'
        params = {"memberId": self.id}
        response = api.post(url, params)
        if response['status'] == 200:
            putong = 0
            simi = 0
            niming = 0
            for item in response['content']['list']:
                if item['name'] == '普通':
                    putong = item['value']
                    if putong > 8388600:
                        putong = 8388607
                elif item['name'] == '匿名':
                    niming = item['value']
                elif item['name'] == '私密':
                    simi = item['value']

            db = DBAction('pocket48')
            db.data_operate("update member set putong=%s,simi=%s,niming=%s where memberid=%s", (putong, simi, niming, self.id))